<template>
  <div class="login-page">
    <div class="login-box">
      <el-form
        ref="ruleFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0px"
        class="login-form"
      >
        <div class="login-header-box">{{ title }}</div>

        <el-row class="form-line">
          <el-col>
            <el-form-item prop="loginName">
              <el-input
                v-model="loginForm.loginName"
                clearable
                auto-complete="off"
                placeholder="账号"
                :prefix-icon="useRenderIcon(User)"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="form-line">
          <el-col>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                show-password
                auto-complete="off"
                placeholder="密码"
                :prefix-icon="useRenderIcon(Lock)"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="countError >= 3" class="form-line form-icon">
          <el-col :span="2" />
          <el-col :span="12">
            <el-form-item prop="code" class="code-error">
              <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" />
            </el-form-item>
          </el-col>
          <el-col :span="10" class="code-box">
            <img :src="codeUrl" alt="code" @click="getCode" />
          </el-col>
        </el-row>

        <el-row class="form-line">
          <el-col :span="22">
            <el-form-item>
              <el-checkbox v-model="loginForm.rememberMe" class="remember-me">记住我</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="form-line">
          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              class="login-btn"
              @click.prevent="onLogin(ruleFormRef)"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import Lock from '@iconify-icons/ri/lock-fill'
import User from '@iconify-icons/ri/user-3-fill'
import { encrypt } from '@wlydfe/core'
import { useRenderIcon } from '@/components/WlIcon/src/hooks'
import { useDataThemeChange } from '@/layout/hooks/useDataThemeChange'
import { useLayout } from '@/layout/hooks/useLayout'
import { useNav } from '@/layout/hooks/useNav'
import { getTopMenu, initRouter } from '@/router/utils'
import { useUserStore } from '@/store/user'
import { message } from '@/utils/message'
import { loginRules } from './utils/rule'

defineOptions({ name: 'Login' })
const { dataTheme, dataThemeChange } = useDataThemeChange()

dataTheme.value = false
dataThemeChange()

const router = useRouter()
const ruleFormRef = ref<FormInstance>()

const { initStorage } = useLayout()
initStorage()

const userStore = useUserStore()
const { title } = useNav()

const countError = ref<number>(0)
const codeUrl = ref<string>('')
const loading = ref<boolean>(false)
const loginForm = reactive({
  loginName: 'finadmin',
  password: 'cs123456',
  code: '',
  rememberMe: '',
})

function getCode() {
  // TODO
}

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      loading.value = true
      const key = 'f#62($0!=4^F824.'
      const loginParams = {
        ...loginForm,
        password: encrypt(loginForm.password, key),
      }
      userStore
        .doLogin(loginParams)
        .then(() => {
          // 获取后端路由
          return initRouter().then(() => {
            router.push(getTopMenu(true).path ?? '/').then(() => {
              message('登录成功', { type: 'success' })
            })
          })
        })
        .finally(() => (loading.value = false))
    }
  })
}

/**
 * 使用公共函数，避免`removeEventListener`失效
 *
 * @param root0
 * @param root0.code
 */
function onkeypress({ code }: KeyboardEvent) {
  if (['Enter', 'NumpadEnter'].includes(code)) {
    onLogin(ruleFormRef.value)
  }
}

onMounted(() => {
  window.document.addEventListener('keypress', onkeypress)
})

onBeforeUnmount(() => {
  window.document.removeEventListener('keypress', onkeypress)
})
</script>

<style lang="scss" scoped>
.login-page {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  // background: url('../assets/logo/login_bg.png') no-repeat bottom center;
  background-size: cover;

  .login-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    // background: url("../assets/logo/login-bg.gif") no-repeat bottom center;
    // background-size: cover;
    .video-cover {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .form-line {
    display: flex;
    align-items: center;
    width: 243px;
    margin-bottom: 10px;

    button {
      height: auto !important;
    }

    v-deep .el-input__inner {
      color: #333;
      background: #f5f7fa;
    }
  }

  .logoShow {
    position: fixed;
    top: 50px;
    left: 50px;
    display: flex;
    flex-shrink: 0;
    width: 236px;

    img {
      width: 100%;
    }
  }

  .login-box {
    position: relative;
    z-index: 10;
    display: flex;
    justify-content: center;
    width: 380px;
    padding: 40px 0;
    margin: 0 auto;
    background-color: #fff;

    // background: rgb(0 0 0 / 20%);
    border-radius: 6px;
    box-shadow: 0 3px 10px 1px rgb(101 107 168 / 22%);

    // box-shadow: 0px 3px 10px 1px rgba(101,107,168,0.22);
    .login-header-box {
      margin-bottom: 25px;
      font-family: 'Source Han Sans CN';
      font-size: 28px;
      font-weight: bold;
      color: #333;
      text-align: center;
    }

    .login-header-title {
      margin-bottom: 47px;
      font-family: 'Source Han Sans CN';
      font-size: 13px;
      font-weight: 400;
      line-height: 18px;
      color: #666;
      text-align: center;
    }

    .login-form {
      // padding: 40px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 220px;
      margin: 0 auto;

      .el-form-item {
        width: 100%;
      }

      .remember-me {
        v-deep .el-checkbox__label {
          color: #333;
        }
      }
    }
  }

  .login-btn {
    width: 100%;
  }

  .code-box {
    height: 36px;
    padding-left: 10px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  // .login-form .el-input {
  //   width: 100% !important;
  //   height: 36px !important;
  //   background: rgba(149, 149, 149, 0.18);
  //   border: none;
  // }
  .el-col {
    flex-shrink: 0;
  }

  .el-block {
    height: 1px;
  }

  .el-form-item--small.el-form-item {
    margin-bottom: 28px;
  }

  .password-box {
    width: 600px;
    padding: 20px;

    .tip {
      padding-left: 38px;
      margin-bottom: 20px;
    }

    .level-wrapper {
      padding-left: 30px;
      margin-bottom: 20px;

      .level-box {
        width: 120px;
        height: 16px;
        margin-right: 2px;
        background-color: #e7e6e5;

        &.active {
          background-color: #fd7d14;
        }
      }

      p {
        padding: 0 10px;
        line-height: 16px;
      }
    }

    .btn-group {
      margin-top: 36px;

      button {
        width: 120px;
        height: 30px;
        padding: 0;
      }
    }
  }
}

:deep(.el-input__inner) {
  height: 36px;
}
</style>
